package com.jyx.order.service;

import com.alibaba.fastjson.JSON;
import com.jyx.framework.domain.course.CourseBase;
import com.jyx.framework.domain.course.CourseMarket;
import com.jyx.framework.domain.course.CoursePic;
import com.jyx.framework.domain.course.CoursePub;
import com.jyx.framework.domain.course.ext.TeachplanNode;
import com.jyx.framework.domain.order.JyxOrders;
import com.jyx.framework.domain.order.JyxOrdersDetail;
import com.jyx.framework.domain.order.JyxOrdersPay;
import com.jyx.framework.domain.order.response.*;
import com.jyx.framework.domain.portalview.PreViewCourse;
import com.jyx.framework.domain.ucenter.response.AuthCode;
import com.jyx.framework.exception.ExceptionCast;
import com.jyx.framework.model.response.CommonCode;
import com.jyx.framework.utils.GenerateOrderNum;
import com.jyx.order.client.CoursePubClient;
import com.jyx.order.dao.JyxOrdersDetailsRepository;
import com.jyx.order.dao.JyxOrdersPayRepository;
import com.jyx.order.dao.JyxOrdersRepository;
import com.jyx.order.dao.PreViewCourseRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class OrderService {

    @Autowired
    JyxOrdersRepository jyxOrdersRepository;
    @Autowired
    JyxOrdersDetailsRepository jyxOrdersDetailsRepository;
    @Autowired
    CoursePubClient coursePubClient;
    @Autowired
    PreViewCourseRepository preViewCourseRepository;
    @Value("${leef.jyxOrder.payCode}")
    String payId;
    @Autowired
    JyxOrdersPayRepository jyxOrdersPayRepository;

    @Transactional
    public CreateOrderResult createOrder(String courseId, String userId) {
        if (StringUtils.isEmpty(courseId)) {
            ExceptionCast.cast(OrderCode.ORDER_ADD_GETCOURSEERROR);
        }
        if (StringUtils.isEmpty(userId)) {
            ExceptionCast.cast(CommonCode.UNAUTHENTICATED);
        }
        JyxOrders jyxOrders = new JyxOrders();
        GenerateOrderNum generateOrderNum = new GenerateOrderNum();
        //订单号
        String orderNum = generateOrderNum.generate();
        if(StringUtils.isEmpty(orderNum)){
            ExceptionCast.cast(OrderCode.ORDER_ADD_ORDERNUMERROR);
        }
        jyxOrders.setOrderNumber(orderNum);
        CoursePub coursePub = coursePubClient.getCoursePubById(courseId);
        if (coursePub == null){
            ExceptionCast.cast(OrderCode.ORDER_ADD_ORDERNUMERROR);
        }
        jyxOrders.setInitialPrice(coursePub.getPrice());
        jyxOrders.setPrice(coursePub.getPrice());
        Date date = new Date();
        Date endTime = new Date();
        jyxOrders.setStartTime(date);
        endTime.setTime(date.getTime()+15*60*1000);
        jyxOrders.setEndTime(endTime);
        jyxOrders.setStatus("401001");
        jyxOrders.setUserId(userId);
        /*Map<String, String> map = new HashMap<>();
        map.put("itemId", courseId);
        String details = JSON.toJSONString(map);*/

        //保存jyxOrderDetail
        JyxOrdersDetail jyxOrdersDetail = new JyxOrdersDetail();
        jyxOrdersDetail.setItemId(courseId);
        jyxOrdersDetail.setEndTime(date);
        jyxOrdersDetail.setStartTime(new Date());
        jyxOrdersDetail.setItemNum(1);
        jyxOrdersDetail.setOrderNumber(orderNum);
        jyxOrdersDetail.setItemPrice(coursePub.getPrice());
        jyxOrdersDetail.setValid(coursePub.getValid());

        List<JyxOrdersDetail> jyxOrdersDetails = new ArrayList<>();
        jyxOrdersDetails.add(jyxOrdersDetail);
        String jsonString = JSON.toJSONString(jyxOrdersDetails);
        jyxOrders.setDetails(jsonString);
        Optional<PreViewCourse> optionalPreViewCourse = preViewCourseRepository.findById(courseId);
        PreViewCourse preViewCourse = null;
        if(!optionalPreViewCourse.isPresent()) {
            //保存课程信息
            preViewCourse = new PreViewCourse();
        }else {
            preViewCourse = optionalPreViewCourse.get();
        }
        //id,courseBase  courseMarket  coursePic  teachplan
        CourseBase courseBase = coursePubClient.queryCourseBaseById(courseId);
        CourseMarket courseMarketById = coursePubClient.getCourseMarketById(courseId);
        CoursePic coursePic = coursePubClient.findCoursePic(courseId);
        TeachplanNode teachplanList = coursePubClient.findTeachplanList(courseId);
        preViewCourse.setCoursePic(coursePic);
        preViewCourse.setTeachplan(teachplanList);
        preViewCourse.setCourseBase(courseBase);
        preViewCourse.setCourseMarket(courseMarketById);
        preViewCourse.setId(courseId);
        preViewCourseRepository.save(preViewCourse);
        jyxOrdersRepository.save(jyxOrders);
        jyxOrdersDetailsRepository.save(jyxOrdersDetail);

        return new CreateOrderResult(CommonCode.SUCCESS,jyxOrders);
    }

    public OrderResult getOrderByNum(String orderNum) {
        Optional<JyxOrders> optionalJyxOrders = jyxOrdersRepository.findById(orderNum);
        if(!optionalJyxOrders.isPresent()){
            return new OrderResult(OrderCode.Pay_NOTFOUNDORDER,null);
        }
        return new OrderResult(CommonCode.SUCCESS, optionalJyxOrders.get());
    }

    public PayQrcodeResult createPayQrcode(String orderNumber) {
        Optional<JyxOrders> optionalJyxOrders = jyxOrdersRepository.findById(orderNumber);
        if(!optionalJyxOrders.isPresent()){
            return new PayQrcodeResult(OrderCode.ORDER_FINISH_NOTFOUNDORDER);
        }
        JyxOrders jyxOrders = optionalJyxOrders.get();
        if(jyxOrders.getStatus().equals("401002")){
            PayQrcodeResult payQrcodeResult = new PayQrcodeResult(CommonCode.SUCCESS);
            payQrcodeResult.setCodeUrl(null);
            return payQrcodeResult;
        }

        PayQrcodeResult payQrcodeResult = new PayQrcodeResult(CommonCode.SUCCESS);
        payQrcodeResult.setCodeUrl("http://www.jieyouxiang.xyz:8088/create/order/"+orderNumber+"/"+payId);
        payQrcodeResult.setMoney(jyxOrders.getPrice());
        payQrcodeResult.setOrderNumber(orderNumber);
        return payQrcodeResult;
    }

    public PayOrderResult queryPayResult(String orderNumber) {
        if(StringUtils.isEmpty(orderNumber)){
            return new PayOrderResult(OrderCode.Pay_NOTFOUNDORDER);
        }
        JyxOrdersPay jyxOrdersPay = jyxOrdersPayRepository.findByOrderNumber(orderNumber);
        if(jyxOrdersPay == null || !jyxOrdersPay.getStatus().equals("401002")){
            return new PayOrderResult(CommonCode.SUCCESS,null);
        }
        PayOrderResult payOrderResult = new PayOrderResult(CommonCode.SUCCESS);
        payOrderResult.setJyxOrdersPay(jyxOrdersPay);
        payOrderResult.setOrderNumber(orderNumber);
        return payOrderResult;
    }
}
